//
//  HBEmotion.swift
//  sinaWeibo
//
//  Created by Beans on 16/7/2.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

let HBEmotionViewReuseIdentifier = "HBEmotionViewCell"

class HBEmotionView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = color_HSB_Random()

        // 应判断版本. iOS9.0以后, 使用StackView

        addSubview(collectionView)
        addSubview(emotionToolBarView)
        emotionToolBarView.delegate = self

        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(emotionToolBarView.snp_top)
        }
        emotionToolBarView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(44)
        }
    }

    private func setupCollectionView() {
        collectionView.registerClass(HBEmotionViewCell.self, forCellWithReuseIdentifier: HBEmotionViewReuseIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self

        // 隐藏滚动条; 弹簧; 分页
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.bounces = false
        collectionView.pagingEnabled = true

//        flowLayout.itemSize = collectionView.bounds.size  // 此处无效, layoutSubview中重新布局
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        // 滚动方向
        flowLayout.scrollDirection = .Horizontal

        // MARK: - 默认表情区域 (注意: 选择合适的时机, 若不延时, 显示一片空白, 因为还来不及加载数据)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: .Left, animated: false)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        flowLayout.itemSize = collectionView.bounds.size
    }

    // MARK: - lazy load
    private var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    // 底部栏
    private lazy var emotionToolBarView: HBEmotionToolBarView = HBEmotionToolBarView(frame: CGRectZero)
}

extension HBEmotionView: UICollectionViewDataSource, UICollectionViewDelegate, HBEmotionToolBarViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        printLog("\(HBEmotionManager.getAllEmotion().count)")
        return HBEmotionManager.getAllEmotion().count
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        printLog("\(HBEmotionManager.getAllEmotion()[section].count)")
        return HBEmotionManager.getAllEmotion()[section].count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HBEmotionViewReuseIdentifier, forIndexPath: indexPath) as! HBEmotionViewCell
//        cell.label.text = "第\(indexPath.section)部分, 第\(indexPath.item)页"
        cell.emotions = HBEmotionManager.getAllEmotion()[indexPath.section][indexPath.item]
        return cell
    }

    // 底部toolBar按钮切换item
    func emotionButtonClick(type: HBEmotionType) {
        switch type {
        case .Recent:
            collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Default:
            collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: .Left, animated: false)
        case .Emoji:
            collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 2), atScrollPosition: .Left, animated: false)
        case .Lxh:
            collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 3), atScrollPosition: .Left, animated: false)
        }
    }
}


// MARK: - 自定义cell
class HBEmotionViewCell: UICollectionViewCell {

    var emotions: [HBEmotion]? {
        didSet {
            // 让表情先隐藏, 需要显示的时候在显示出来 (解决'最近'重用的问题)
            for button in emotionsButton {
                button.hidden = true
            }

            // 遍历数据
            for (index, emotion) in emotions!.enumerate() {
                // 1. 取cell对应btn
                let button = emotionsButton[index]
                button.hidden = false
                // 赋值
                button.emotion = emotion

//                // 2. 赋值
//                // 如何去区分图片表情和emoji? 通过对象里emoji与png为空的情况
//
//                // 2.1 图片表情
//                if let png = emotion.png, path = emotion.path {
//                    let imageName = "\(path)/\(png)"    // "\(emotion.path)/\(emotion.png)"未解包
//                    button.setImage(UIImage(named: imageName), forState: .Normal)
//                } else {
//                    // 一定要注意cell重用
//                    button.setImage(nil, forState: .Normal)
//                }
//
//                // 2.2 emoji
//                if let emoji = emotion.emoji {
//                    button.setTitle(emoji, forState: .Normal)
//                } else {
//                    button.setTitle(nil, forState: .Normal)
//                }
            }
        }
    }

    // 定义数组, 保存20个按钮
    private lazy var emotionsButton: [HBEmotionButton] = [HBEmotionButton]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
//        backgroundColor = color_HSB_Random()
        backgroundColor = colorWithHexString(hexString: "0xFFFFCC")

        addChildButtons()
    }

    // MARK: - 添加20个button到cell
    private func addChildButtons() {
        let btnW: CGFloat = bounds.width / 7
        let btnH: CGFloat = bounds.height / 3

        for i in 0..<20 {
            let button = HBEmotionButton()

            let col = i % 7
            let row = i / 7
            button.frame = CGRectMake(CGFloat(col) * btnW, CGFloat(row) * btnH, btnW, btnH)
            button.addTarget(self, action: "childButtonClick:", forControlEvents: .TouchUpInside)

            contentView.addSubview(button)
            emotionsButton.append(button)
        }

        deleteButton.frame = CGRectMake(bounds.width - btnW, bounds.height - btnH, btnW, btnH)
        contentView.addSubview(deleteButton)
    }

    @objc private func childButtonClick(button: HBEmotionButton) {
        // 显示到'最近'表情
        guard let emotion = button.emotion else {
            return
        }
        HBEmotionManager.addRecentEmotion(emotion)

        // 发送通知给publishVc
        // 插入表情   // 通知传递的参数不要放在object(通知发送者), userInfo传递参数
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationTransformEmotion, object: nil, userInfo: ["emotion" : emotion])
    }

    @objc private func deleteButtonClick(button: HBEmotionButton) {
        // 删除功能
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationDeleteEmotion, object: nil, userInfo: nil)
    }

    // MARK: - lazy load
    private lazy var deleteButton: UIButton = {
        let button = UIButton(type: .Custom)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        button.addTarget(self, action: "deleteButtonClick:", forControlEvents: .TouchUpInside)
        return button
    }()
}